package com.itheima.controller;

import com.itheima.anno.Log;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    /*查询部门列表*/
    @GetMapping//@RequestMapping(value = "/depts",method = RequestMethod.GET)//指定请求方式
    public Result list(){
        //System.out.println("查询全部部门");
        log.info("查询全部部门");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }

    /*删除部门-HttpServletRequest*/
    /*@DeleteMapping
    public Result delete(HttpServletRequest request){
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);
        System.out.println("根据ID删除部门：" + id);
        return Result.success();
    }*/

    /*删除部门-@RequestParam*/
    /*@DeleteMapping
    public Result delete(@RequestParam("id") Integer deptId){//声明了@RequestParam一定要传参，required默认为true
        System.out.println("根据ID删除部门：" + deptId);
        return Result.success();
    }*/

    @Log
    /*删除部门-省略@RequestParam（参数名=形参名）*/
    @DeleteMapping
    public Result delete(Integer id){
        //System.out.println("根据ID删除部门：" + id);
        log.info("根据ID删除部门:{}",id);
        deptService.deleteById(id);
        return Result.success();
    }

    @Log
    /*新增部门*/
    @PostMapping
    public Result add(@RequestBody Dept dept){
        //System.out.println("添加部门：" + dept);
        log.info("添加部门:{}",dept);
        deptService.add(dept);
        return Result.success();
    }

    //根据ID查询部门
    /*@GetMapping
    public Result getInfo(@PathVariable("id") Integer id){
        System.out.println("根据ID查询部门：" + id);
        return Result.success();
    }*/

    //根据ID查询部门（省略@PathVariable注解后面的括号：传递过来的参数名=形参名）
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id){
        //System.out.println("根据ID查询部门：" + id);
        log.info("根据ID查询部门:{}",id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    @Log
    //修改部门
    @PutMapping
    public Result update(@RequestBody Dept dept){
        //System.out.println("修改部门：" + dept);
        log.info("修改部门:{}",dept);
        deptService.update(dept);
        return Result.success();
    }
}
